import numpy as np
import pandas as pd

# 1
data = pd.read_csv(r"C:\Users\Administrator\Downloads\作业二需求及数据\Wholesale customers data.csv")
print(data.head(5))
print(data.shape)
# 2
# print(data.info())

# 3
#数据预处理
data.describe()
#在此使用Normalizer---使用方法同MinMaxScaler、StandardScaler
from sklearn.preprocessing import Normalizer
X = data.iloc[:,2:]
normalizer = Normalizer().fit(X)
# Normalizer(copy=True, norm='l2')
X_ = normalizer.transform(X)

#适用轮廓系数找到最优K
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score #轮廓系
import matplotlib.pyplot as plt
score = []
# 将k（簇）值从2变化到20
for i in range(2, 20):
    cluster = KMeans(n_clusters=i, random_state=0).fit(X_)
    score.append(silhouette_score(X_, cluster.labels_))

# plt.plot(range(2, 20), score)
# plt.axvline(pd.DataFrame(score).idxmax()[0] + 2, ls=':')
# plt.show()
# 最优K
cu = pd.DataFrame(score).idxmax()[0] + 2 #2


# 建模及可视化分析
data2 = pd.DataFrame(data=X_,columns=['Fresh','Milk','Grocery','Frozen','Detergents_Paper','Delicassen'])
print(data2.head(4))
#绘制饼状图
cluster = KMeans(n_clusters=3, random_state=0).fit(X_)
y_pred = cluster.labels_
data_1 = pd.DataFrame(y_pred).value_counts()
print(data_1[0])
# print(y_pred)
lables=["0","1","2"]
plt.pie(
    data_1,
    labels=lables,
    autopct="%0f%%",
     )
plt.legend(lables)
plt.show()

#绘制条形图
data2["lable"]=y_pred
cond1 = data2["lable"]==0
cond2 = data2["lable"]==1
cond3 = data2["lable"]==2
y1 = [data2[cond1]['Fresh'].mean(),data2[cond2]['Fresh'].mean(),data2[cond3]['Fresh'].mean()]
y2 = [data2[cond1]['Milk'].mean(),data2[cond2]['Milk'].mean(),data2[cond3]['Milk'].mean()]
y3 = [data2[cond1]['Grocery'].mean(),data2[cond2]['Grocery'].mean(),data2[cond3]['Grocery'].mean()]
y4 = [data2[cond1]['Frozen'].mean(),data2[cond2]['Frozen'].mean(),data2[cond3]['Frozen'].mean()]
y5 = [data2[cond1]['Detergents_Paper'].mean(),data2[cond2]['Detergents_Paper'].mean(),data2[cond3]['Detergents_Paper'].mean()]
y6 = [data2[cond1]['Delicassen'].mean(),data2[cond2]['Delicassen'].mean(),data2[cond3]['Delicassen'].mean()]
print(y1)
print(y2)
print(y3)
print(y4)
print(y5)
print(y6)

x = np.arange(3)
# lables = np.array(["G1","G2","G3"])
width = 0.4
plt.bar(x-width/2,y1,color="orange",width=width)
plt.bar(x+width/2,y2,color="blue",width=width)
plt.bar(x+2*width/2,y3,color="yellow",width=width)
plt.bar(x+3*width/2,y4,color="red",width=width)
plt.bar(x+4*width/2,y5,color="#6A5ACD",width=width)
plt.bar(x+4*width/2,y6,color="#548B54",width=width)



plt.legend(['Fresh','Milk','Grocery','Frozen','Detergents_Paper','Delicassen'])
plt.show()
